package com.example.learn_gl_android.anglib.core.gl.shader

import android.opengl.GLES30
import com.example.learn_gl_android.anglib.util.MyGLUtil
import com.example.learn_gl_android.anglib.core.gl.COLOR_COMPONENT_COUNT
import com.example.learn_gl_android.anglib.core.gl.ServiceLocator
import com.example.learn_gl_android.anglib.core.gl.VERTEX_COMPONENT_COUNT
import java.nio.FloatBuffer

class SimpleShader {
    private var mProgram  = 0
    private var muMVPMatrixLocation = 0
    private var maPositionLocation = 0
    private var maColorLocation = 0

    private var vShaderSource  = ""
    private var fShaderSource = ""

    private var mVertexCount  = 0
    private var mVertexBuffer: FloatBuffer = FloatBuffer.allocate(0)
    private var mColorBuffer: FloatBuffer = FloatBuffer.allocate(0)
    private var mMVPMatrix = FloatArray(0)

     init {
        val glView = ServiceLocator.getService()
        vShaderSource = MyGLUtil.readFile("vertex.glsl", glView.resources)
        fShaderSource = MyGLUtil.readFile("frag.glsl", glView.resources)

        mProgram = MyGLUtil.createSimpleProgram(vShaderSource, fShaderSource)

        maPositionLocation = GLES30.glGetAttribLocation(mProgram, "aPosition")
        maColorLocation = GLES30.glGetAttribLocation(mProgram, "aColor")
        muMVPMatrixLocation = GLES30.glGetUniformLocation(mProgram, "uMVPMatrix")
    }

    fun vertexBuffer(vertexBuffer: FloatBuffer){
        mVertexBuffer = vertexBuffer
    }

    fun colorBuffer(colorBuffer : FloatBuffer){
        mColorBuffer = colorBuffer
    }

    fun matrixBuffer(mvpMatrix : FloatArray){
        mMVPMatrix = mvpMatrix
    }

    fun vertexCount(vertexCount : Int){
        mVertexCount = vertexCount
    }

    fun draw(){
        GLES30.glUseProgram(mProgram)

        GLES30.glUniformMatrix4fv(muMVPMatrixLocation, 1, false,
                                    mMVPMatrix, 0)

        GLES30.glVertexAttribPointer(maPositionLocation, VERTEX_COMPONENT_COUNT, GLES30.GL_FLOAT,
                            false, MyGLUtil.lenForNFloat(VERTEX_COMPONENT_COUNT), mVertexBuffer)
        GLES30.glVertexAttribPointer(maColorLocation, COLOR_COMPONENT_COUNT, GLES30.GL_FLOAT,
                            false, MyGLUtil.lenForNFloat(COLOR_COMPONENT_COUNT), mColorBuffer)

        GLES30.glEnableVertexAttribArray(maPositionLocation)
        GLES30.glEnableVertexAttribArray(maColorLocation)

        GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, mVertexCount)
    }

}